#!/bin/sh
################################################################################
# lcdproc
################################################################################
. /etc/rc.d/functions

start() {

    /usr/bin/logger -s -t minimyth -p "local0.info" "[init.d/lcdproc] Starting..."

    if [ "x${MM_LCDPROC_ENABLED}" = "xyes" ] ; then

        # Only start the LCDd daemon when one is not running already.
        if [ -z "`/bin/pidof LCDd`" ] ; then
            # Load user configured kernel module.
            if [ -n "${MM_LCDPROC_KERNEL_MODULE}" ] ; then
                /sbin/modprobe ${MM_LCDPROC_KERNEL_MODULE} ${MM_LCDPROC_KERNEL_MODULE_OPTIONS}
                # Wait up to 60 seconds for the device to appear in the device file system.
                delay=0
                while [ ! -e ${MM_LCDPROC_DEVICE} ] && [ ${delay} -lt 60 ] ; do
                    /bin/sleep 1
                    delay=$((delay + 1))
                    /usr/bin/logger -s -t minimyth -p "local0.info" "[init.d/lcdproc] waiting for LCD/VFD device (${delay} seconds) ..."
                done
                if [ ! -e ${MM_LCDPROC_DEVICE} ] ; then
                    /usr/bin/logger -s -t minimyth -p "local0.err" "[init.d/lcdproc] error: timed out waiting for LCD/VFD device!"
                    exit 1
                fi
            fi

            # Load the LCDproc configuration file.
            if [ ! -e /etc/LCDd.conf ] ; then
                if [ -n "${MM_LCDPROC_DRIVER}" ] ; then
                    if [ -e /etc/lcdproc.d/LCDd.conf.d/LCDd.conf.${MM_LCDPROC_DRIVER} ] ; then
                        cp /etc/lcdproc.d/LCDd.conf.d/LCDd.conf.${MM_LCDPROC_DRIVER} /etc/LCDd.conf
                    else
                        cp /etc/lcdproc.d/LCDd.conf.d/LCDd.conf                      /etc/LCDd.conf
                    fi
                fi
            fi

            if [ -e /etc/LCDd.conf ] ; then
                # Set the driver and device.
                /bin/sed -i "s%@MM_LCDPROC_DRIVER@%${MM_LCDPROC_DRIVER}%" /etc/LCDd.conf
                /bin/sed -i "s%@MM_LCDPROC_DEVICE@%${MM_LCDPROC_DEVICE}%" /etc/LCDd.conf
                # Start LCDproc LCDd daemon and Myth LCD server.
                /usr/sbin/LCDd -c /etc/LCDd.conf
            fi
        fi

        # Enable LCD in MythTV.
        if [ -n "`/bin/pidof LCDd`" ] ; then
            mm_mythdb_settings_set "LCDEnable" "1"
        else
            mm_mythdb_settings_set "LCDEnable" "0"
        fi

    fi

    /usr/bin/logger -s -t minimyth -p "local0.info" "[init.d/lcdproc] Started with return code=0..."

    return 0
}


stop() {
    mm_message_output info "stopping LCD/VFD daemon ..."

    if [ -n "`/bin/pidof LCDd`" ] ; then
        /usr/bin/killall LCDd
    fi

    return 0
}

case $1 in
    start) start ;;
    stop)  stop  ;;
esac

exit 0
